//===================================================获取用户ID=========================================================
var id=$.cookie("MYID");
//var id="7c7fdd2ef9a51aed";
if(id){

}else{
    location.href="index.html";
}
var roomidreg=/(roomid=)([a-zA-Z0-9]*)/;
var roomid = urlfrom.match(roomidreg).splice("=")[2];
console.log("roomid:"+roomid);
//聊天页面返回键
$("#chatpagegobackbtn").click(function(){
    history.go(-1);
});
//环信建立连接
var conn = new WebIM.connection({
    https: WebIM.config.https,
    url: WebIM.config.xmppURL,
    isAutoLogin: WebIM.config.isAutoLogin,
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions
});
//获取聊天对象信息
var otherimg="";//保存他人头像
var myimg="";//保存自己头像
//自己的信息
$.ajax({
    type: "post",
    //提交的网址
    url: userurl,
    //提交的数据
    data: { "userId": id},
    //返回数据的格式
    datatype: "json",//"xml", "html", "script", "json", "jsonp", "text".
    success:function(data){
        if(data.Data.userAva){
            myimg="<img src='http://42.62.66.198:8003/"+data.Data.userAva+"'>";
        }else{
            myimg="<img src='img/loseimg.png'>";
        }
    }
});
//时间方法---------------------------------------------------------
function GetDateT(){
    var d,s;
    d = new Date();
    //s = d.getYear() + "-";             //取年份
    //s = s + (d.getMonth() + 1) + "-";//取月份
    s += d.getDate() + " ";         //取日期
    s += d.getHours() + ":";       //取小时
    s += d.getMinutes() + ":";    //取分
    //s += d.getSeconds();         //取秒
    return(s);
}
var oldtime=GetDateT();//当前时间
//保存对应图片-----------------------------------------------------
var map={
    '[):]':'ee_1.png',
    '[:D]': 'ee_2.png',
    '[;)]': 'ee_3.png',
    '[:-o]': 'ee_4.png',
    '[:p]': 'ee_5.png',
    '[(H)]': 'ee_6.png',
    '[:@]': 'ee_7.png',
    '[:s]': 'ee_8.png',
    '[:$]': 'ee_9.png',
    '[:(]': 'ee_10.png',
    '[:\'(]': 'ee_11.png',
    '[:|]': 'ee_12.png',
    '[(a)]': 'ee_13.png',
    '[8o|]': 'ee_14.png',
    '[8-|]': 'ee_15.png',
    '[+o(]': 'ee_16.png',
    '[<o)]': 'ee_17.png',
    '[|-)]': 'ee_18.png',
    '[*-)]': 'ee_19.png',
    '[:-#]': 'ee_20.png',
    '[:-*]': 'ee_21.png',
    '[^o)]': 'ee_22.png',
    '[8-)]': 'ee_23.png',
    '[(|)]': 'ee_24.png',
    '[(u)]': 'ee_25.png',
    '[(S)]': 'ee_26.png',
    '[(*)]': 'ee_27.png',
    '[(#)]': 'ee_28.png',
    '[(R)]': 'ee_29.png',
    '[({)]': 'ee_30.png',
    '[(})]': 'ee_31.png',
    '[(k)]': 'ee_32.png',
    '[(F)]': 'ee_33.png',
    '[(W)]': 'ee_34.png',
    '[(D)]': 'ee_35.png'
};
//登录
var options = {
    apiUrl: WebIM.config.apiURL,
    user:id,
    pwd:id,
    appKey: "pulu#pulu"
};
conn.open(options);
//环信保存用户信息 及 成员信息---------------------------------------------------------------
var masterid="";//群主ID
var memberids=[];
//收信息--获取成员头像----------------------------------------------------------------
//获取环信成员信息----------------------------------
var queryRoomMember = function () {
    var member = '';
    conn.queryRoomMember({
        roomId: roomid,
        success: function (members) {
            if(members&&members.length>0){
                var tim= 0,len=members.length;
                for (var o in members) {
                    tim++;
                    member = members[o].jid;
                    //console.log("群组成员：",member);
                    //console.log(member.match(/^[^pulu\#pulu_][a-zA-Z0-9]/)[0]);
                    memberids.push(member.match(/[pulu#pulu_0-9a-zA-Z]+/)[0].replace("pulu#pulu_",""));
                    if(tim==len){
                        console.log("保存的群组成员id:",memberids);
                        //获取服务器所有成员信息----------------------------
                        $.ajax({
                            type:"post",
                            dataType: "json",
                            url:gethxmemberurl,
                            data:{"persons":memberids},
                            success:function(m){
                                console.log("获取的成员头像");
                                console.log(m);
                                if(m.Data&&m.Data.length>0){
                                    for(var i=0;i<m.Data.length;i++){
                                        $("<div class='imgbox'> <div> <img src='"+imgurl+m.Data[i].headImg+"'/> </div> <div class='username'>"+m.Data[i].nick+"</div> </div>").insertBefore("#addmemberbtn");
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
    });
};
conn.listen({
    onOpened: function ( message ) {          //连接成功回调
        //如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
        conn.setPresence();
        console.log("连接成功:");
        //console.log(message);
        // 获取群组信息------------------------------------------------------------------
        var roomidreg=/(roomid=)([a-zA-Z0-9]*)/;
        var roomid = urlfrom.match(roomidreg).splice("=")[2];
        //获取群信息--------------------------------------
        var queryGroupInfo = function () {
            console.log("获取群信息");
            conn.queryRoomInfo({
                roomId:roomid,
                success: function (d) {
                    console.log(d);
                    if(d&& d.length>0){
                        for(var i=0;i<d.length;i++){
                            if(d[i].affiliation=="owner"){
                                masterid= d[i].jid.match(/[pulu#pulu_0-9a-zA-Z]+/)[0].replace("pulu#pulu_","");
                                console.log("获取群主信息：",masterid);
                                console.log("当前ID:",id);
                                masterid==id?$("#delmemberbtn").css("display","block"):$("#delmemberbtn").css("display","none");
                                if(masterid==id){
                                    alert("我是群主");
                                    $("#delmemberbtn").css("display","block");
                                }
                            }
                        }
                    }
                },
                error: function () {
                    console.log('Error!');
                }
            });
        };
        queryGroupInfo();
        //获取环信成员信息----------------------------------
        queryRoomMember();

    },
    onTextMessage: function ( message ) {
        console.log("收到的文本消息");
        console.log(message);
        var arr1=message.data;
        console.log(arr1);
        var reg=/\[[^\s]+\]/g;
        if(arr1.match(reg)){
            var arr3=arr1.match(reg);
            console.log(arr3);
            var faceimg="";
            for(var rr= 0;rr<arr3.length;rr++){
                arr3[rr].index=rr;
                if(arr3[rr].match(reg)){
                    arr1=arr1.replace(arr3[rr],"<img src='faces/"+map[arr3[rr]]+"'>");
                };
                console.log(arr1);
            }
        }
        //获取接收消息的时间-----------
        var newtime=GetDateT();
        console.log(newtime);
        $("#chatbody").append("<div class='otherchatword'> <div class='img'> "+otherimg+" </div> <div class='word'><p class='arrow'></p>"+arr1+"</div> </div>");
        $(".img").height($(".img").width());
    },//收到文本消息
    onClosed: function ( message ) {console.log("1");},         //连接关闭回调
    onEmojiMessage: function ( message ) {console.log("2");},   //收到表情消息
    onPictureMessage: function ( message ) {

    }, //收到图片消息
    onCmdMessage: function ( message ) {console.log("4");},     //收到命令消息
    onAudioMessage: function ( message ) {console.log("5");},   //收到音频消息
    onLocationMessage: function ( message ) {console.log("6");},//收到位置消息
    onFileMessage: function ( message ) {console.log("7");},    //收到文件消息
    onVideoMessage: function ( message ) {console.log("8");},   //收到视频消息
    onPresence: function ( message ) {console.log("9");console.log(message);},       //收到联系人订阅请求、处理群组、聊天室被踢解散等消息
    onRoster: function ( message ) {console.log("10");},         //处理好友申请
    onInviteMessage: function ( message ) {console.log("11");},  //处理群组邀请
    onOnline: function () {console.log("本机网络连接成功12");},                  //本机网络连接成功
    onOffline: function () {console.log("本机网络掉线13");}                 //本机网络掉线
    //onError: function ( message ) {console.log("失败回调14");console.log(message)}           //失败回调
});

